<!--
 * @Description  : 借阅单详情
 * @Author       : zhao
 * @Date         : 2022-07-13 13:40:25
 * @LastEditors  : zhao
 * @LastEditTime : 2023-02-02 15:53:30
-->
<template>
    <div class='BorrowDetails height_Fill'>
        <zBack :content="'借阅单详情'" />
        <div class="BorrowDetails_content">
            <div ref="borderPrintRef">
                <el-descriptions title="">
                    <el-descriptions-item label="姓名:">{{ userData.val.realName }}</el-descriptions-item>
                    <el-descriptions-item label="身份证号:">{{ userData.val.idNumber }}</el-descriptions-item>
                    <el-descriptions-item label="联系方式:">{{ userData.val.phone }}</el-descriptions-item>
                    <el-descriptions-item label="工作单位:">{{ userData.val.workCompany }}</el-descriptions-item>

                    <el-descriptions-item label="单位地址:">{{ userData.val.companyAddress }}</el-descriptions-item>
                    <el-descriptions-item label="单位性质:">{{ userData.val.unitProperties }}</el-descriptions-item>
                    <!-- <el-descriptions-item label="借阅时间:">{{ userData.val.date }}</el-descriptions-item> -->

                    <el-descriptions-item label="邮箱:">{{ userData.val.mail }}</el-descriptions-item>

                    <el-descriptions-item label="涉密号:">{{ userData.val.certificateNo }}
                    </el-descriptions-item>
                    <el-descriptions-item label="资料使用范围:">{{ userData.val.dataUseArea }}</el-descriptions-item>
                    <el-descriptions-item label="资料用途:" span="3">{{ userData.val.dataPurpose }}</el-descriptions-item>

                    <el-descriptions-item label="介绍信:">
                        <span class="cursor" @click="Preview('介绍信')">
                            {{ userData.val.introductionLetterName }}
                        </span>
                    </el-descriptions-item>
                    <el-descriptions-item label="任务书:">
                        <span class="cursor" @click="Preview('任务书')">
                            {{ userData.val.assignmentName }}
                        </span>

                    </el-descriptions-item>
                </el-descriptions>

                <div>
                    <el-collapse v-model="state.activeNames" @change="handleChange">
                        <el-collapse-item :title="i.title" :name="index" v-for="i, index in detailsData.val">
                            <div>
                                <el-descriptions title="" border :column="4">
                                    <el-descriptions-item label="档号:" label-class-name="my_label">{{ i.snNo }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label="资料名称:" :span="3" label-class-name="my_label">{{
                                            i.title
                                    }}
                                    </el-descriptions-item>

                                </el-descriptions>
                                <div class="title">
                                    目录
                                </div>
                                <div>
                                    <!-- <zTables :tableHeader="tableHeaders" :edit="edit" /> -->
                                    <el-table ref="multipleTableRef" :data="i.data" style="width: 100%"
                                        @selection-change="handleSelectionChange" border>
                                        <el-table-column type="selection" width="55" />
                                        <el-table-column label="资料类别">
                                            <template #default="scope">{{ scope.row.DataType }}</template>
                                        </el-table-column>
                                        <el-table-column label="件号">
                                            <template #default="scope">{{ scope.row.FileNO }}</template>
                                        </el-table-column>
                                        <el-table-column label="文件名" show-overflow-tooltip>
                                            <template #default="scope">{{ scope.row.FileName }}</template>
                                        </el-table-column>
                                        <el-table-column label="附注">
                                            <template #default="scope">
                                                <el-input v-model="scope.row.Remark"
                                                    v-if="edit || scope.row.state == '待审核'" placeholder="请输入附注"
                                                    size="default"
                                                    @blur="handleBlurRemark(i, scope.row, scope.row.Remark)" />

                                                <span v-else>{{ scope.row.Remark }} </span>

                                            </template>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>

                        </el-collapse-item>

                    </el-collapse>
                </div>
            </div>

            <div class="footer">
                <div v-if="rowData.state == '待审核'">
                    <el-button type="primary" size="default" @click="onSubmit('通过')">通过</el-button>
                    <el-button type="danger" size="default" @click="onSubmit('驳回')">驳回</el-button>
                </div>
                <div v-if="rowData.state == '已驳回'">
                    <!-- <el-button type="danger" size="default" @click="onSubmit('返回')">返回</el-button> -->

                </div>
                <div v-if="rowData.state == '审核通过'">
                    <el-button type="" size="default" @click="onSubmit('退出编辑')" v-if="edit">退出编辑</el-button>
                    <el-button type="primary" size="default" @click="onSubmit('编辑')" v-if="!edit">编辑</el-button>
                    <el-button type="primary" size="default" @click="onSubmit('提交')" v-if="edit">提交</el-button>
                    <el-button type="danger" size="default" @click="onSubmit('删除')" v-if="edit">删除</el-button>
                    <el-button type="danger" size="default" @click="onSubmit('驳回')">驳回</el-button>
                    <!-- <el-button type="primary" size="default" @click="onSubmit('打印')">打印</el-button> -->
                    <zdownload />
                </div>
                <div v-if="rowData.state == '已完成'">
                    <!-- <el-button type="danger" size="default" @click="onSubmit('返回')">返回</el-button> -->

                </div>
                <div v-if="rowData.state == '已过期'">
                    <el-button type="" size="default" @click="onSubmit('退出编辑')" v-if="edit">退出编辑</el-button>
                    <el-button type="primary" size="default" @click="onSubmit('编辑')" v-if="!edit">编辑</el-button>
                    <el-button type="primary" size="default" @click="onSubmit('提交')" v-if="edit">提交</el-button>
                    <el-button type="danger" size="default" @click="onSubmit('驳回')">驳回</el-button>
                    <!-- <el-button type="primary" size="default" @click="onSubmit('打印')">打印</el-button> -->
                    <zdownload />
                </div>
            </div>

            <el-dialog v-model="dialogVisible" title="审核意见" width="30%" :before-close="handleClose">
                <div>
                    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px"
                        class="demo-ruleForm" status-icon>

                        <el-form-item label="审核意见">
                            <div v-if="dialogtypes == '通过'" style="width:100%">
                                <el-checkbox v-model="reviewComments1" label="" size="large" />
                                <el-input :title="ruleForm.val.reviewCommentsPass"
                                    v-model="ruleForm.val.reviewCommentsPass" style="width:80%;padding-left: 10px"
                                    size="default " />
                            </div>
                            <div v-if="dialogtypes == '驳回'" style="width:100%">
                                <div style="width:100%">
                                    <el-checkbox v-model="reviewComments2" label="" size="large" />
                                    <el-input v-model="ruleForm.val.reviewCommentsReject1"
                                        style="width:80%;padding-left: 10px" size="default " />
                                </div>
                                <div style="width:100%">
                                    <el-checkbox v-model="reviewComments3" label="" size="large" />
                                    <el-input v-model="ruleForm.val.reviewCommentsReject2"
                                        style="width:80%;padding-left: 10px" size="default " />
                                </div>
                            </div>
                            <el-input v-model="ruleForm.reviewComments" type="textarea"
                                style="margin-left: 14px;padding-left: 10px;width:80%" />
                        </el-form-item>
                        <el-form-item style="width:100%;text-align: center;" class="el-form-item-button">
                            <el-button @click="dialogVisible = false">返回</el-button>
                            <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">

                    </span>
                </template>
            </el-dialog>

            <zPreview ref="dialogVisiblePre" />
        </div>
    </div>
</template>

<script lang="ts">
export default {
    name: "BorrowDetails",



};

</script>

<script setup lang='ts'>
import { ref, reactive, } from 'vue'
import { toRaw } from '@vue/reactivity'
import zPreview from "/@/components/zPreview/index.vue"
import zBack from "/@/components/zBack/index.vue"
import zdownload from '/@/components/zTable/compinents/download.vue'
import printJs from 'print-js';
import { useTableInfo } from '/@/stores/ztable'
import { useBorrow } from '/@/stores/borrow'
import { usePreview } from '/@/stores/preview'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import zpublic from "/@/utils/public.ts"
import Row from 'element-plus/es/components/row/src/row'

const {
    zTable,
    zTableType,

} = useTableInfo()

const { CSGetBorrowingFormDetails,
    CSGetBorrowingFormBtnPass,
    CSGetBorrowingFormBtnReject,
    CSGetBorrowingFormDetailsSave,
    CSDeleteBorrowingFormDetails,
    CSGetBorrowingFormBtnFinish,
    CSGetBorrowingFormDetailsReject
} = useBorrow()

const useBorrows = useBorrow()
zTableType.border = true
zTableType.menu = false
let state = reactive({
    remark: "",
    activeNames: <any>[0],
    RemarkData: <any>[],
    selectRowData: <any>[]
})
let borderPrintRef = ref()
const tableHeader = [
    { prop: 'DataType', label: '资料类型', width: '' },
    { prop: 'FileNO', label: '件号', width: '' },
    { prop: 'FileName', label: '文件名', width: '' },
    { prop: 'FileNamess', label: '附注', width: '' },
]
const tableHeaders = ref(tableHeader);
let edit = ref(false)


let dialogVisible = ref(false)
let reviewComments1 = ref(false)
let reviewComments2 = ref(false)
let reviewComments3 = ref(false)
let userData: any = reactive({
    val: {}
})
let detailsData: any = reactive({
    val: {}
})


const router = useRouter()
const goBack = () => {
    router.push({ path: '/borrow' })
}
//模态窗
const ruleForm: any = reactive({
    val: {
        reviewCommentsReject1: '上传的材料存在问题。',
        reviewCommentsReject2: '申请范围与用途不符。',
        reviewComments: '',
        reviewCommentsPass: '申请已通过审核，请于30日内，由申请人本人，持申请材料原件到馆确认并领取地质资料。',
    }
})
const ruleFormRef = ref<FormInstance>()
let dialogtypes: any = ref("")
const rules = reactive<FormRules>({
    reviewComments: [
        {
            required: true,
            message: '请输入审核意见',
            trigger: 'change',
        },
    ],
})
//关闭，模态窗
const handleClose = (done: () => void) => {
    done()
}
const submitForm = async (formEl: FormInstance | undefined) => {
    const formdata = toRaw(ruleForm)

    if (!formEl) return
    await formEl.validate(async (valid: any, fields: any) => {
        if (valid) {
            if (dialogtypes.value === "通过") {
                if (!reviewComments1.value && !formdata.reviewComments) return ElMessage.error("请输入审核意见")


                let num = 1
                let obj1 = {
                    tableNo: rowData.tableNo,
                    reviewComments: "",
                    listDetail: state.RemarkData
                }
                if (reviewComments1.value) {
                    obj1.reviewComments += (num + '.' + ruleForm.val.reviewCommentsPass)
                    num++
                }
                if (formdata.reviewComments) {
                    obj1.reviewComments += (num + '.' + formdata.reviewComments)
                }


                const dataPass = await CSGetBorrowingFormBtnPass(obj1)
                if (dataPass.code === 200) {
                    ElMessage.success(dataPass.msg || "提交成功")
                    dialogVisible.value = true
                    goBack()
                } else {
                    ElMessage.error(dataPass.msg || "提交失败")
                }

            }
            if (dialogtypes.value === "驳回") {
                if (!reviewComments2.value && !reviewComments3.value && !formdata.reviewComments) return ElMessage.error("请输入审核意见")

                let num2 = 1
                let obj2 = {
                    tableNo: rowData.tableNo,
                    reviewComments: "",
                    listDetail: state.RemarkData
                }

                if (reviewComments2.value) {
                    obj2.reviewComments += (num2 + '.' + ruleForm.val.reviewCommentsReject1)
                    num2++
                }
                if (reviewComments3.value) {
                    obj2.reviewComments += (num2 + '.' + ruleForm.val.reviewCommentsReject2)
                    num2++
                }
                if (formdata.reviewComments) {
                    obj2.reviewComments += (num2 + '.' + formdata.reviewComments)
                }

                const dataReject = await CSGetBorrowingFormBtnReject(obj2)

                if (dataReject.code === 200) {
                    ElMessage.success(dataReject.msg || "提交成功")
                    dialogVisible.value = true
                    goBack()
                } else {
                    ElMessage.error(dataReject.msg || "提交失败")
                }
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const onPrintJs = () => {

    printJs({
        printable: borderPrintRef.value,
        type: 'html',
        css: ['//at.alicdn.com/t/font_2298093_o73r8wjdhlg.css', '//unpkg.com/element-plus/dist/index.css'],
        scanStyles: false,
        style: `@media print{.mb15{margin-bottom:15px;}.el-button--small i.iconfont{font-size: 12px !important;margin-right: 5px;}}`,
    });
};


//获取详情数据
// const rowData: any = toRaw(zTable.rowData)
const rowData: any = JSON.parse(sessionStorage.getItem("rowdata") || '{}')

const getDetailsData = async () => {

    useBorrows.downloadObj = { tableNo: rowData.tableNo }
    let data = null

    if (rowData.menuType == "menu2") {
     data = await CSGetBorrowingFormDetailsReject({ tableNo: rowData.tableNo })
        
    } else {
     data = await CSGetBorrowingFormDetails({ tableNo: rowData.tableNo })
        
    }
    if (data.code != 200) return ElMessage.error(data.msg || '请求出错')
    userData.val = data.data.partHead
    let preindex = 0
    detailsData.val = data.data.partBottom.reduce((pre: any, item: any, index: any) => {
        let data = {
            snNo: item.snNo,
            title: item.title,
            indeterminate: false,
            selected: false,

            data: []
        }

        let fileData = { ...JSON.parse(item.fileInfo), id: index, state: rowData.state, selected: false, fromInfoId: item.fromInfoId, }

        if (pre.length == 0) {
            pre.push(data)
            pre[preindex].data.push(fileData)
            return pre
        }
        if (pre.some((e: any) => e.title == item.title)) {
            pre[preindex].data.push(fileData)
        } else {
            pre.push(data)
            preindex++
            pre[preindex].data.push(fileData)
        }
        return pre

    }, [])

}
getDetailsData()


//设置按钮
const setbuttom = () => {
    if (rowData.state == 2) {

    }
}
setbuttom()


//折叠面板
const handleChange = () => { }


const onSubmit = async (types: any) => {
    if (types == "退出编辑") {
        edit.value = false
        getDetailsData()
        // return goBack()
    }
    if (types == "提交") submit()
    if (types == "删除") deletes()


    if (types == "编辑") {
        state.RemarkData = []
        edit.value = true
    }
    if (types == "通过" || types == "驳回") {
        dialogVisible.value = true
        dialogtypes.value = types

    }
    if (types == "打印") {

        open()
        setTimeout(() => {
            onPrintJs()
        }, 500);
    }

}
//提交
const submit = async () => {


    const data = await CSGetBorrowingFormDetailsSave({ tableNo: rowData.tableNo, listDetail: state.RemarkData })
    if (data.code == 200) {
        const datas = await CSGetBorrowingFormBtnFinish({ tableNo: rowData.tableNo })
        if (datas.code == 200) goBack()
    }
}
//删除
const deletes = async () => {
    let arr = <any>[]
    state.selectRowData.map((e: any) => { arr.push(e.fromInfoId) })

    let arr2 = {
        id: arr,
        tableNo:rowData.tableNo
     }
    const data = await CSDeleteBorrowingFormDetails(arr2)
    if (data.code == 200) getDetailsData()
}
//标注change事件
const handleBlurRemark = (i: any, row: any, val: any) => {
    // if (!val) {
    //     state.RemarkData.map((e: any, index: any) => {
    //         if (e.fromInfoId == row.fromInfoId) {
    //             delete state.RemarkData[index]
    //         }
    //     })
    // } else {

    // }

    state.RemarkData.map((e: any, index: any) => {
        if (e.fromInfoId == row.fromInfoId) {
            // delete state.RemarkData[index]
            state.RemarkData.splice(index, 1)
        }
    })
    let fileinfo = {
        FileNO: row.FileNO,
        FileName: row.FileName,
        Remark: row.Remark,
        DataType: row.DataType,
    }
    let obj = {
        fromInfoId: row.fromInfoId,
        fileInfo: JSON.stringify(fileinfo)
    }

    state.RemarkData.push(obj)



}
//表格选中
const handleSelectionChange = (val: any) => { state.selectRowData = val }
const dialogVisiblePre = ref()
//预览
const usePreviews = usePreview()
const Preview = async (name: string,) => {

    let res = null
    if (name == "介绍信") {
        res = await usePreviews.getIntroductionLetter({ id: rowData.id })

    } else if (name == "任务书") {
        res = await usePreviews.getAssignment({ id: rowData.id })

    }

    if (res.type === "text/plain" || res.type === "application/json") {

        // 说明是普通对象数据，读取信息
        const fileReader = <any>new FileReader()
        fileReader.onloadend = () => {
            try {
                const jsonData = JSON.parse(fileReader.result) // 说明是普通对象数据，后台转换失败
                // 后台信息
                ElMessage.error(jsonData.msg || "请求出错")
            } catch (err) {
                // 解析成对象失败，说明是正常的文件流
                // 下载文件
                console.log("ss", err)
            }
        }

        fileReader.readAsText(res)

    } else {
        dialogVisiblePre.value.dialogVisible = true

        usePreviews.previewType.url = zpublic.Preview(res)
        usePreviews.previewType.type = res.type
        usePreviews.previewType.data = res.res


    }
}

//全部展开
const open = () => {
    state.activeNames = []
    detailsData.val.map((e: any, index: any) => state.activeNames.push(index))

}


</script>
<style lang='scss' scoped>
.BorrowDetails {
    padding: 20px;
    background: white;

    .BorrowDetails_content {
        margin: 0 15px;
        padding: 10px;
        border: 1px solid #eee;

        .footer {
            text-align: center;
            padding: 10px 0;
        }
    }



    .el-collapse {
        border: 1px solid #eee;
        padding: 10px;



        .title {
            text-align: center;
            padding: 10px;
            border-left: 1px solid #eee;
            border-right: 1px solid #eee;
        }
    }
}

::v-deep(.my_label) {
    background: #fff !important;
}

.el-form-item-button {
    ::v-deep .el-form-item__content {
        display: flex;
        margin-left: 0px !important;
        justify-content: center;
    }
}
</style>